package com.lottery.im.module.chat.ui;

import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import butterknife.BindView;
import butterknife.OnClick;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.fondesa.recyclerviewdivider.RecyclerViewDivider;
import com.lottery.im.MyApplication;
import com.lottery.im.R;
import com.lottery.im.base.BaseSwipeFragment;
import com.lottery.im.constant.Constants;
import com.lottery.im.module.chat.adapter.CreateGroupFriendAdapter;
import com.lottery.im.module.tim.model.FriendProfile;
import com.lottery.im.module.tim.model.FriendshipInfo;
import com.lottery.im.module.tim.model.GroupInfo;
import com.tencent.imsdk.TIMGroupManager;
import com.tencent.imsdk.TIMGroupMemberInfo;
import com.tencent.imsdk.TIMGroupMemberRoleType;
import com.tencent.imsdk.TIMValueCallBack;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 创建群聊 选择好友
 */
public class CreateGroupFriendFragment extends BaseSwipeFragment {

  @BindView(R.id.tv_title) TextView mTvTitle;
  @BindView(R.id.list) RecyclerView mList;
  @BindView(R.id.tv_empty_tip) TextView mTvEmptyTip;
  @BindView(R.id.btn_confirm) Button mBtnConfirm;

  private List<FriendProfile> mFriendProfiles = new ArrayList<>();
  private CreateGroupFriendAdapter mAdapter;
  private ArrayList<String> mSelectIds = new ArrayList<>();

  @Override protected int getLayoutResId() {
    return R.layout.fragment_create_group_friend;
  }

  @Override protected void initPresenter() {
    initView();
  }

  private void initView() {
    mTvTitle.setText("创建群聊");
    mList.setLayoutManager(new LinearLayoutManager(mActivity));
    RecyclerViewDivider.with(mActivity)
        .color(ContextCompat.getColor(mActivity, R.color.windowBackground))
        .size((int) mActivity.getResources().getDimension(R.dimen.line_size))
        .hideLastDivider()
        .build()
        .addTo(mList);
    mAdapter = new CreateGroupFriendAdapter(mFriendProfiles, mSelectIds);
    mAdapter.setOnItemClickListener((adapter, view, position) -> setCheck(position));
    mList.setAdapter(mAdapter);
    getFriends();
  }

  @OnClick({ R.id.iv_back, R.id.layout_group, R.id.btn_confirm })
  public void onViewClicked(View view) {
    switch (view.getId()) {
      case R.id.iv_back:
        popBackStack();
        break;
      case R.id.layout_group:
        startFragment(new CreateGroupGroupFragment());
        break;
      case R.id.btn_confirm:
        confirm();
        break;
    }
  }

  /**
   * @param position 点击的position
   * 修改选择状态
   */
  private void setCheck(int position) {

    if (mFriendProfiles.get(position).getIdentify()
        .equals(MyApplication.getInstance().getThirdAccId())
        || mFriendProfiles.get(position).getIdentify().equals(MyApplication.getInstance().getUserInfo().getQqServiceName())
        || mFriendProfiles.get(position).getIdentify().equals(MyApplication.getInstance().getUserInfo().getQqFeedBackName())) {
      return;
    }

    if (mSelectIds.contains(mFriendProfiles.get(position).getIdentify())) {
      mSelectIds.remove(mFriendProfiles.get(position).getIdentify());
    } else {
      mSelectIds.add(mFriendProfiles.get(position).getIdentify());
    }
    mAdapter.setSelectIds(mSelectIds, position);
    if (mSelectIds.size() > 0) {
      mBtnConfirm.setEnabled(true);
    } else {
      mBtnConfirm.setEnabled(false);
    }
  }

  /**
   * 获取好友列表
   */
  private void getFriends() {
    mFriendProfiles.clear();
    Map<String, List<FriendProfile>> friends = FriendshipInfo.getInstance().getFriends();
    List<String> groupNames = FriendshipInfo.getInstance().getGroups();
    for (String groupName : groupNames) {
      for (FriendProfile friendProfile : friends.get(groupName)) {
        mFriendProfiles.add(friendProfile);
      }
    }
    mAdapter.notifyDataSetChanged();
    if (mFriendProfiles.size() == 0) {
      mTvEmptyTip.setVisibility(View.VISIBLE);
      mList.setVisibility(View.GONE);
    } else {
      mTvEmptyTip.setVisibility(View.GONE);
      mList.setVisibility(View.VISIBLE);
    }
  }

  /**
   * 选择完成，确定邀请
   */
  private void confirm() {
    showLoadingDialog();
    TIMGroupManager.CreateGroupParam param =
        new TIMGroupManager.CreateGroupParam(GroupInfo.publicGroup, Constants.DEFAULT_GROUP_NAME);

    List<TIMGroupMemberInfo> infos = new ArrayList<>();
    for (String id : mSelectIds) {
      TIMGroupMemberInfo member = new TIMGroupMemberInfo(id);
      member.setRoleType(TIMGroupMemberRoleType.Normal);
      infos.add(member);
    }
    param.setMembers(infos);

    TIMGroupManager.getInstance().createGroup(param, new TIMValueCallBack<String>() {
      @Override public void onError(int i, String s) {
        cancelLoadingDialog();
        showToast("创建失败，请稍后再试～");
      }

      @Override public void onSuccess(String s) {
        cancelLoadingDialog();
        showToast("创建成功");
        popBackStack();
      }
    });
  }
}
